<!--vue模板-->
<template>
  <div class="root">

    <!--工具条-->
    <div class="toolbar">
      <el-button type="primary" size="small">保存并新增</el-button>
      <el-button type="primary" size="small" @click="save">保存</el-button>
    </div>

    <!--第一行 -->
    <el-row style="margin-top: 20px">
      <el-col :span="8">
        供应商:<input type="text" @click="isshowsupllier = true" placeholder="请单击选择供应商" class="ipt"
          v-model="purchaseForm.supplierName" />
      </el-col>
      <el-col :span="8">
        单据日期:
        <el-date-picker type="date" value-format="YYYY-MM-DD" placeholder="请选择" v-model="purchaseForm.billDate"
          size="small" />
      </el-col>
      <el-col :span="8"> 单据编号：CG1232342 </el-col>
    </el-row>

    <div class="detail">
      <!--明细-->
      <div class="detail-title">
        <span>采购明细</span>
        <el-button type="primary" size="small" @click="addRow">增行</el-button>
        <el-button type="primary" size="small" @click="delRow">删行</el-button>
      </div>
      <!--列表-->
      <el-table :data="tableData" style="width: 100%" stripe border @cell-click="cellck" ref="purchaseRef">
        <el-table-column type="selection" width="80" header-algin="center" align="center" />

        <el-table-column type="index" label="序号" width="80" header-algin="center" align="center" />

        <el-table-column prop="goodsname" label="商品" width="180" header-algin="center" align="center">
          <template v-slot="{ row, column }">
            <span v-if="row.show[column.property] == undefined">{{
        row.goodsname
      }}</span>
            <el-input v-else v-model="row.goodsname" placeholder="点击选择商品" @click="isshowchoose = true"></el-input>
          </template>
        </el-table-column>

        <el-table-column prop="unit" label="单位" width="80" header-algin="center" align="center" />

        <el-table-column prop="warehouse" label="仓库" width="120" header-algin="center" align="center" />

        <el-table-column prop="num" label="数量" width="140" header-algin="center" align="center">
          <template v-slot="{ row, column }">
            <span v-if="row.show[column.property] == undefined">{{
        row.num
      }}</span>
            <el-input-number v-else v-model="row.num" size="small" :min="0"></el-input-number>
          </template>
        </el-table-column>

        <el-table-column prop="price" label="单价" width="140" header-algin="center" align="center">
          <template v-slot="{ row, column }">
            <span v-if="row.show[column.property] == undefined">{{
        row.price
      }}</span>
            <el-input-number v-else v-model="row.price" size="small" :min="0" :precision="2"></el-input-number>
          </template>
        </el-table-column>

        <el-table-column prop="rate" label="折扣率" width="140" header-algin="center" align="center">
          <template v-slot="{ row, column }">
            <span v-if="row.show[column.property] == undefined">{{
        row.rate
      }}</span>
            <el-input-number v-else v-model="row.rate" size="small" :min="0" :max="100"
              :precision="2"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column prop="rateMoney" label="折扣额" width="100" header-algin="center" align="center" />
        <el-table-column prop="money" label="采购金额" width="100" header-algin="center" align="center" />
        <el-table-column prop="note" label="备注" width="180" header-algin="center" align="center">
          <template v-slot="{ row, column }">
            <span v-if="row.show[column.property] == undefined">{{
        row.note
      }}</span>
            <el-input v-else v-model="row.note" size="small"></el-input>
          </template>
        </el-table-column>
      </el-table>

      <!--备注信息-->
      <div>
        <input type="text" placeholder="填写订单备注信息" class="note" v-model="purchaseForm.note"></input>
      </div>
    </div>

    <!--优惠-->
    <el-row style="margin-top:20px;">
      <el-col :span="6">优惠率:<input type="text" class="ipt" v-model="purchaseForm.rate" />%</el-col>
      <el-col :span="6">优惠金额:<input type="text" class="ipt" v-model="purchaseForm.rateMoney" /></el-col>
      <el-col :span="6">优惠后金额:<input type="text" class="ipt" v-model="purchaseForm.money" /></el-col>
      <el-col :span="6">本次付款:<input type="text" class="ipt" v-model="purchaseForm.pay" /></el-col>
    </el-row>

    <!--账户合同 -->
    <el-row style="margin-top:20px;">
      <el-col :span="6">结算账号:<input type="text" class="ipt" v-model="purchaseForm.accountId" /></el-col>
      <el-col :span="6">本次欠款:<input type="text" class="ipt" v-model="purchaseForm.debt" /></el-col>
      <el-col :span="12">采购合同:
        <el-upload v-model:file-list="fileList" class="upload-demo" :action="host + '/upload'"
          :on-success="handleChange" :on-remove="rm">
          <el-button type="primary" size="small">上传</el-button>
          <template #tip>
            <div class="el-upload__tip">
              jpg/png 格式的合同
            </div>
          </template>
        </el-upload>

      </el-col>
    </el-row>

    <!--制单人-->
    <el-row style="margin-top:20px;">
      <el-col :span="6">制单人:<input type="text" class="ipt" v-model="purchaseForm.prepared" /></el-col>
      <el-col :span="18">&nbsp;</el-col>
    </el-row>

    <!--选择商品-->
    <ChooseGoods :visible="isshowchoose" @choose="choose" @close="isshowchoose = false"></ChooseGoods>

    <!--选择供应商-->
    <ChooseSupplier :visible="isshowsupllier" @close="isshowsupllier = false" @choose="chg"></ChooseSupplier>
  </div>
</template>

<!--vue 组件选项定义-->
<script setup>
import { ref, onMounted, watch } from "vue";
import { ElMessage } from "element-plus";
import { updateShipment,getDetail }from '@/api/shipment/shipment'
import ChooseGoods from '@/views/set/goods/ChooseGoods.vue'
import ChooseSupplier from '@/views/set/supplier/ChooseSupplier.vue'
import host from '@/utils/env.js'
import { useRoute } from 'vue-router'

//获取路由 参数对象信息
const route = useRoute();
const tableData = ref([]);

const lastRow = ref({}); //记录上一次双击的是哪一行
const purchaseRef = ref(null); //表格引用

const isshowchoose = ref(false);//是否显示商品选择框
const isshowsupllier = ref(false);//是否显示选择供应商

const fileList = ref([]);//上传合同列表

const purchaseForm = ref({
  supplierId: 0,
  supplierName: "",
  billDate: "",
  note: "",
  rate: 0,
  rateMoney: 0,
  money: 0,
  pay: 0,
  accountId: 0,
  debt: 0,
  prepared: "",
  contracts: []

});

//侦听器
watch(tableData, (n) => {
  //遍历表格明细  计算折扣额  采购金额
  tableData.value.forEach(row => {

    if (row.num > 0 && row.price > 0) {
      //未优惠前总金额
      let total = row.num * row.price;
      //计算折扣额
      let tmpRateMoney = 0;
      if (row.rate > 0) {
        tmpRateMoney = total * (row.rate / 100);
        //更新当前行的折扣金额
        row.rateMoney = tmpRateMoney;
      }

      //计算采购金额 总金额 减去折扣金额
      row.money = total - tmpRateMoney;

    }


  });
}, {
  deep: true
});

//方法

//查询详情方法
async function queryDetail(id) {
  let res = await getDetail(id);
  if (res.code == 200) {
    purchaseForm.value = res.data;
    //获取明细
    let tmp = res.data.shipmentDetailList;
    //遍历明细 给每一个对象增加属性show={}
    tmp.forEach(el => {
      el.show = {};
    });
    tableData.value = tmp;
  }
}


//文件列表移除
function rm(updateFile) {
  //console.log(updateFile);
  //将指定的文件 从purhcaseForm中移除
  //获取要删除的合同路径
  let path = updateFile.response.data;
  let index = -1;
  //查询
  for (let i = 0, len = purchaseForm.value.contracts.length; i < len; i++) {
    //临时对象
    let tmp = purchaseForm.value.contracts[i];
    if (tmp.path == path) {
      index = i;
      break;
    }
  }

  if (index != -1) {
    purchaseForm.value.contracts.splice(index, 1);
  }
}
//上传
function handleChange(res, uploadFile) {
  //获取接口返回数据
  if (res.code == 200) {
    //上传成功 获取上传后的  路径 及附件名称
    let tmp = {};
    tmp.path = res.data;
    tmp.filename = uploadFile.name;
    purchaseForm.value.contracts.push(tmp);
  }
}

//--选择供应商--
function chg(row) {
  purchaseForm.value.supplierId = row.id;
  purchaseForm.value.supplierName = row.name;
}

//选择商品
function choose(rows) {

  if (rows.length == 0)
    return;
  //获取选择行的索引
  let index = -1;

  //遍历表格数据 查询选择的第一个对象的位置
  for (let i = 0, len = tableData.value.length; i < len; i++) {
    //临时对象
    let tmp = tableData.value[i];
    if (tmp == lastRow.value) {
      index = i;
      break;
    }
  }

  if (index == -1)
    return;

  //遍历选择的商品
  for (let i = 0, len = rows.length; i < len; i++) {
    //临时对象
    let obj = tableData.value[index];
    obj.goodsid = rows[i].id;
    obj.goodsname = rows[i].name;
    obj.price = rows[i].price;
    obj.unit = rows[i].unit;
    obj.warehouse = rows[i].warehouseName;
    index++;
    if (index >= tableData.value.length) {
      addRow();
    }
  }

  //先清空之前 添加的所有属性
  if (lastRow.value.show != undefined) {
    //清空标志属性
    lastRow.value.show = {};
  }


}

//保存
async function save() {

  let detail = [];//保存用户填写的明细
  //遍历表格数据
  tableData.value.forEach(r => {
    //判断当前对象中是否选择了商品 如果是  加入到明细
    if (r.goodsname != undefined && r.goodsname != "") {
      detail.push(r);
    }
  })

  if (detail.length == 0) {
    ElMessage({
      message: "采购明细不能为空！",
      type: "warning"
    });
    return;
  }
  // 参数值
  let data = purchaseForm.value;//采购单基本信息
  //将明细加入采购单
  data.shipmentDetailList = detail;



  //保存
  let res = await updateShipment(data);
  if (res.code == 200) {
    ElMessage({
      message: "修改成功",
      type: "success"
    });
  }
}

//单元格双击事件
function cellck(row, column) {
  //先清空之前 添加的所有属性
  if (lastRow.value.show != undefined) {
    //清空标志属性
    lastRow.value.show = {};
  }

  let tmp = column.property;
  row.show[tmp] = true;

  //记录双击的行
  lastRow.value = row;
}


//新增行
function addRow() {
  tableData.value.push({
    goodsid: "",
    goodsname: "",
    unit: "",
    warehouse: "",
    num: 0,
    price: 0,
    rate: 0,
    rateMoney: 0,
    money: 0,
    note: "",
    show: {}
  });
}

//删除行
function delRow() {
  let rows = purchaseRef.value.getSelectionRows();
  if (rows.length == 0) {
    ElMessage({
      message: "请选择要删除的行！",
      type: "warning"
    });
  }

  //遍历要删除的行
  rows.forEach(r => {
    removeData(r);
  });
}

//从tableData移除 行  r 代表要移除的行
function removeData(r) {
  for (let i = 0, len = tableData.value.length; i < len; i++) {
    //获取当前行对象
    let tmp = tableData.value[i];
    //判断tmp是否是要删除的对象r
    if (tmp == r) {
      console.log("删除", tmp);
      tableData.value.splice(i, 1);
      break; //终止循环
    }
  }
}

//
onMounted(() => {
  queryDetail(route.params.id);
});
</script>

<!--vue样式 scoped当前样式只适用于当前组件-->
<style scoped>
.root {
  border: #ebeef5 solid 1px;
  background-color: #fff;
  height: 100%;
  padding-left: 20px;
}

.toolbar {
  height: 40px;
  line-height: 40px;
  text-align: right;
  padding-right: 20px;
}

.ipt {
  width: 200px;
  border-style: none;
  outline-style: none;
  border-bottom: #ebeef5 solid 1px;
  padding-left: 10px;
}

.detail {
  margin-right: 20px;
  margin-top: 30px;
  padding-left: 10px;
}

.detail-title {
  height: 40px;
  line-height: 40px;
  border: #ebeef5 solid 1px;
  border-bottom-style: none;
  padding-left: 10px;
}

.detail-title button {
  margin-left: 10px;
}

.note {
  width: 100%;
  border-style: none;
  outline-style: none;
  border-bottom: #ebeef5 solid 1px;
  margin-top: 20px;
}
</style>
